package com.gh.controller;

import com.gh.entity.JsonResult;
import com.gh.entity.Student;
import com.gh.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
@Scope("prototype")
public class StudentController {

    @Autowired
    private StudentService service;

    @RequestMapping("/findAllStudent.do")
    public List<Student> findAll(int currPage, int pageSize) {
        List<Integer> list = new ArrayList<Integer>();
        int start = (currPage - 1) * pageSize;
        list.add(start);
        list.add(pageSize);
        try {
            List<Student> list2 = service.findAll(list);
            return list2;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @RequestMapping("/findTotal.do")
    public Integer findTotal() throws Exception {
        Integer count = service.findTotal();
        return count;
    }

    @RequestMapping("/add.do")
    public JsonResult addStudent(Student student) {
        try {
            service.add(student);
            return new JsonResult(true, "添加成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new JsonResult(false, "添加失败");
    }

    @RequestMapping("/update.do")
    public JsonResult updateStudent(Student updateForm) {
        try {
            service.update(updateForm);
            return new JsonResult(true, "修改成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new JsonResult(false, "修改失败");
    }


    @RequestMapping("/deleteStudent.do")
    public JsonResult deleteStudent(int id) {
        try {
            service.delete(id);
            return new JsonResult(true, "删除成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new JsonResult(false, "删除失败");
    }

    @RequestMapping("/findByAddress.do")
    public List<Student> findByAddress(String address) {
        try {
            List<Student> list = service.findByAddress(address);
            return list;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping("/findByName.do")
    public List<Student> findByName(String name) {
        try {
            List<Student> list = service.findByName(name);
            return list;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping("/findById.do")
    public List<Student> findById(int id) {
        try {
            List<Student> list = service.findById(id);
            return list;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
